package com.escope.casemanager.service.impl;

import com.escope.casemanager.dao.*;
import com.escope.casemanager.model.CaseExample;
import com.escope.casemanager.model.HttpResult;
import com.escope.casemanager.model.PageModel;
import com.escope.casemanager.model.SysMessage;
import com.escope.casemanager.service.SysMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Administrator
 * 2024/3/15
 */
@Transactional(rollbackFor = Exception.class)
@Service("sysMessageService")
public class SysMessageServiceImpl implements SysMessageService {

    @Autowired
    private SysMessageDao sysMessageDao;


    @Override
    public void saveSysMessage(SysMessage message) {
        message.setCreateTime(new Date());
        message.setStatus("0");
        sysMessageDao.save(message);
    }

    @Override
    public HttpResult findByPage(PageModel page) {
        //页码：前端从1开始，jpa从0开始，做个转换
        Pageable pageable = PageRequest.of(page.getPageNum() - 1, page.getPageSize(), Sort.by(Sort.Direction.DESC, "id"));
        Page<SysMessage> cePage = sysMessageDao.findAll(new Specification<SysMessage>() {
            @Override
            public Predicate toPredicate(Root<SysMessage> root, CriteriaQuery<?> query, CriteriaBuilder builder) {

                List<Predicate> preds = new ArrayList<>();

                return builder.and(preds.toArray(new Predicate[0]));
            }
        }, pageable);
        page.setData(cePage.getContent());
        page.setTatalPageNum(cePage.getTotalPages());
        page.setTotalNum(cePage.getTotalElements());
        return HttpResult.ok(page);
    }

    @Override
    public HttpResult findById(Long id) {
        return HttpResult.ok(sysMessageDao.findById(id));
    }
}
